import re
from paddleocr import PaddleOCR
import time
import cv2
import math

import screenshot_adb
import numpy as np

ocr = PaddleOCR(
    use_doc_orientation_classify=False,
    use_doc_unwarping=False,
    use_textline_orientation=False)  # 文本检测+文本识别

empty_region = (135,51,191,259)
chat_region = (556,713, 443,152)
map_region = (1346, 2, 253, 216)
master_region = (1407,48, 187,144)


def get_current_position(device_serial=None, max_retry=3):
    """
    获取当前角色位置（需要根据游戏实际情况实现）
    :return: (x, y) 坐标
    """
    for _ in range(max_retry):
        try:
            map_img = screenshot_adb.fast_screenshot(map_region, device_serial)
            map_np = np.array(map_img.convert('RGB'))
            map_result = ocr.predict(map_np)

            if map_result and len(map_result) > 0:
                for line in map_result:

                    # map_name = line['rec_texts'][0]  地图
                    # attack_pattern = line['rec_texts'][2]  攻击模式
                    text = line['rec_texts'][-1]  # 坐标
                    # 严格匹配 "数字:数字" 格式（支持 123:456 或 123 : 456）
                    match = re.match(r'^\s*(\d+)\s*:\s*(\d+)\s*$', text.strip())
                    # coordinate = [int(match.group(1)), int(match.group(2))]
                    if match:
                        return (int(match.group(1)), int(match.group(2)))

        except Exception as e:
            print(f"坐标获取失败（重试中）: {str(e)}")
            time.sleep(1)

    return None




def get_empty_name(device_serial=None, max_retry=3):
    """带重试机制的地图名称获取"""
    for _ in range(max_retry):

        empty_img = screenshot_adb.fast_screenshot(empty_region, device_serial=device_serial)
        empty_np = np.array(empty_img.convert('RGB'))
        empty_result = ocr.predict(empty_np)

        if empty_result and len(empty_result) > 0:
            for line in empty_result:
                return line['rec_texts']
        else:
            return None




def detect_red(device_serial=None):
    """
    精确检测 FF0000-F90000 区间的红色
    :param screenshot_region: 截图区域 (x, y, width, height)
    :param device_serial: ADB设备序列号
    :return: bool 是否找到目标红色
    """
    # 1. 获取截图并转换为OpenCV格式
    screenshot = screenshot_adb.fast_screenshot(master_region, device_serial)
    img_rgb = np.array(screenshot.convert('RGB'))
    img_hsv = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2HSV)

    # 2. 定义红色区间 (FF0000-F90000 对应的HSV范围)
    lower_red1 = np.array([0, 100, 100])     # 赤红色 (0°~10°)
    upper_red1 = np.array([10, 255, 255])
    lower_red2 = np.array([170, 100, 100])   # 深红色 (170°~180°)
    upper_red2 = np.array([180, 255, 255])

    # 3. 创建红色掩膜
    mask1 = cv2.inRange(img_hsv, lower_red1, upper_red1)
    mask2 = cv2.inRange(img_hsv, lower_red2, upper_red2)
    red_mask = cv2.bitwise_or(mask1, mask2)

    # 4. 检测是否存在红色像素
    return cv2.countNonZero(red_mask) > 0


def detect_red_with_stats(device_serial=None, reference_point=(101, 79)):
    """
    检测红色并返回统计信息
    :param device_serial: ADB设备序列号
    :param reference_point: 参考点坐标 (x, y)
    :return: dict {
        'farthest_point': (x, y),  # 最远红色坐标
        'max_distance': float,      # 最远距离
        'nearby_count': int,        # 最远点30像素内的红色像素数
        'total_red': int            # 总红色像素数
    } 或 None (如果未找到红色)
    """
    # 1. 获取截图并处理
    screenshot = screenshot_adb.fast_screenshot(master_region, device_serial)
    img_rgb = np.array(screenshot.convert('RGB'))
    img_hsv = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2HSV)

    # 2. 定义红色区间
    lower_red1 = np.array([0, 100, 100])
    upper_red1 = np.array([10, 255, 255])
    lower_red2 = np.array([170, 100, 100])
    upper_red2 = np.array([180, 255, 255])

    # 3. 创建红色掩膜
    mask1 = cv2.inRange(img_hsv, lower_red1, upper_red1)
    mask2 = cv2.inRange(img_hsv, lower_red2, upper_red2)
    red_mask = cv2.bitwise_or(mask1, mask2)

    # 4. 获取所有红色像素坐标
    red_pixels = np.argwhere(red_mask > 0)
    total_red = len(red_pixels)
    if total_red == 0:
        return None

    # 5. 找出最远点
    ref_x, ref_y = reference_point
    max_distance = -1
    farthest_point = None

    for y, x in red_pixels:
        distance = math.sqrt((x - ref_x) ** 2 + (y - ref_y) ** 2)
        if distance > max_distance:
            max_distance = distance
            farthest_point = (x, y)

    # 6. 计算30像素范围内的点数
    if farthest_point:
        fx, fy = farthest_point
        nearby_count = 0
        threshold = 30  # 像素距离阈值

        # 使用numpy向量化计算提高性能
        distances = np.sqrt(
            (red_pixels[:, 1] - fx) ** 2 +
            (red_pixels[:, 0] - fy) ** 2
        )
        nearby_count = np.sum(distances <= threshold)
    else:
        nearby_count = 0

    return {
        'farthest_point': farthest_point,
        'max_distance': max_distance,
        'nearby_count': int(nearby_count),
        'total_red': total_red
    }



if __name__ == '__main__':


    for i in range(1000):

        coord = get_current_position(device_serial=None)

        empty = get_empty_name()
        is_red = detect_red()
        print("找到红色" if is_red else "未找到红色")

        print(coord, empty)

        # empty_img = screenshot_adb.fast_screenshot(empty_region, device_serial=None)
        # empty_np = np.array(empty_img.convert('RGB'))
        # empty_result = ocr.predict(empty_np)
        #
        # for res in empty_result:
        #     print(res['rec_texts'])
        # print(empty_result['res']['rec_texts'])
